<?php

namespace app\adminapi\controller;

use OSS\Core\OssException;
use OSS\OssClient;
use think\Request;

class Upload extends Common
{
    static private $initConfigFlag = false;
    static private $accessKeyId = '';
    static private $accessKeySecret = '';
    static private $endpoint = '';
    static private $bucket = '';

    static private $ossClient = null;

    /**
     * 参数配置
     */
    static private function initConfig()
    {
        if (self::$initConfigFlag) {
            return;
        }

        self::$accessKeyId     = 'H2oBhmlbamtVCSqH';
        self::$accessKeySecret = 'IWmlc0FujQiu9GKZOCXC09soKkuF2M';
        self::$endpoint        = 'oss-cn-hangzhou.aliyuncs.com';
        self::$bucket          = 'nclavi';
        self::$initConfigFlag  = true;
    }

    /**
     * 创建上传对象
     * @return OssClient|void|null
     */
    static private function getOssClient()
    {
        if (!self::$ossClient) {
            self::initConfig();
            try {
                self::$ossClient = new OssClient(self::$accessKeyId, self::$accessKeySecret, self::$endpoint, false);
            } catch (OssException $e) {
                echo json_encode(['status'=>0,'msg'=> "创建oss对象失败，".$e->getMessage() ]);
                exit();
            }
        }
        return self::$ossClient;
    }

    /**
     * 文件上传
     * @param Request $request
     * @return string
     */
    public function uploadfile(Request $request)
    {
        $file = $request->file('file');
        if(!$file){
            return json(['status'=>0,'msg'=> '文件未上传' ]);
        }

//        try {
//            $this->validate(
//                ['file' => $file],
//                ['file'=>'fileSize:52428800'],
//                ['file.fileSize' => '上传文件过大']
//            );
//        } catch (\Exception $e) {
//            return json(['status'=>0,'msg'=> $e->getMessage() ]);
//        }

        $ossClient = self::getOssClient();
        if (!$ossClient) {
            return json(['status'=>0,'msg'=> '创建oss对象失败' ]);
        }

        // 获取文件后缀
        $getOriginalName = pathinfo($file->getOriginalName(),PATHINFO_EXTENSION);
        $object = 'upload/'.date("Ym").'/'.md5(uniqid(mt_rand(), true)).'.'.$getOriginalName;

        try {
            $info = $ossClient->uploadFile(self::$bucket, $object, $file->getRealPath());
            $data['url'] = $info['info']['url'];
            $data['name'] = $file->getOriginalName();
            return json(['status'=>200,'data'=> $data ]);
        } catch (OssException $e) {
            return json(['status'=>0,'msg'=> "oss上传文件失败，".$e->getMessage() ]);
        }
    }

    /**
     * 文件上传
     * @param Request $request
     * @return string
     */
    public function upload_base64(Request $request)
    {
        $base64 = $request->param('base64');
        if(!$base64){
            return json(['status'=>0,'msg'=> '文件未上传' ]);
        }

        if (preg_match($preg = '|^data:image/(.*?);base64,|i', $base64)) {
            [$ext, $img] = explode('|||', preg_replace($preg, '$1|||', $base64));
            if (empty($ext) || !in_array(strtolower($ext), ['png', 'jpg', 'jpeg'])) {
                return json(['status'=>0,'msg'=> '图片格式异常！' ]);
            }
        } else {
            return json(['status'=>0,'msg'=> '解析内容失败！' ]);
        }

        $ossClient = self::getOssClient();
        if (!$ossClient) {
            return json(['status'=>0,'msg'=> '创建oss对象失败' ]);
        }

        // 获取文件后缀
        $getOriginalName = $ext;
        $md5file = md5(time()).'.'.$getOriginalName;
        $object = 'upload/'.date("Ym").'/'.$md5file;

        $info = $ossClient->putObject(self::$bucket,$object,base64_decode($img));

        try {
            $info = $ossClient->putObject(self::$bucket,$object,base64_decode($img));
            $data['url'] = $info['info']['url'];
            $data['name'] = $md5file;
            return json(['status'=>200,'data'=> $data ]);
        } catch (OssException $e) {
            return json(['status'=>0,'msg'=> 'oss上传文件失败']);
        }
    }
}